<!--
 * @Author: 小花
 * @Date: 2022-04-02 13:52:36
 * @LastEditors: 小花
 * @LastEditTime: 2022-04-26 12:24:19
 * @Description: 缴费页面
-->
<template>
  <div class='chargeOn_container'>
    <el-divider content-position="left">订单完结</el-divider>
    <div style="display: block;text-align: right;">
      <el-button type="primary" size="small" v-if="checkPayStatus()" @click="pay">缴费</el-button>
    </div>

    <el-descriptions class="descriptionsStyle" :column="3" size="small" border
      v-for="(item , idx) in tableData" :key="idx">
      <el-descriptions-item>
        <template #label>
          <i class="el-icon-s-order"></i>
          订单单号
        </template>
        {{item.orderId}}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <i class="el-icon-s-order"></i>
          申报单号
        </template>
        {{item.applyId}}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <i class="el-icon-tickets"></i>
          材料名称
        </template>
        {{item.materialLibraryEntity.materialName}}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <i class="fa fa-jpy"></i>
          材料单价
        </template>
        {{ item.materialPrice }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <i class="el-icon-pie-chart"></i>
          申报数量
        </template>
        {{item.takeAmount}}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <i class="fa fa-jpy"></i>
          总计金额
        </template>
        <span style="color: #f56c6c;font-weight: bold;">
          {{(item.materialPrice*item.takeAmount).toFixed(1)}}
        </span>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <i class="fa fa-calendar"></i>
          申报时间
        </template>
        {{ item.applyTime }}
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <i class="fa fa-spinner"></i>
          申报状态
        </template>
        <el-tag size="small" :type="['danger','success'].at(item.applyStatus)" effect="plain">
          {{ [ '未完成', '已完成' ].at(item.applyStatus) }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <i class="fa fa-spinner"></i>
          收费状态
        </template>
        <el-tag size="small" :type="['danger', 'success' ].at(item.chargeOn)" effect="plain">
          {{ [ '未开启', '已开启' ].at(item.chargeOn) }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <i class="fa fa-spinner"></i>
          缴纳状态
        </template>
        <el-tag size="small" :type="[ 'danger', 'success' ].at(item.chargeStatus)" effect="plain">
          {{ [ '未缴费', '已缴费' ].at(item.chargeStatus) }}
        </el-tag>
      </el-descriptions-item>
    </el-descriptions>

    <el-dialog v-model="dialogVisible" width="50%">
      <div class="dialog-header">
        <span class="dialog-header-price"> <i class="fa fa-jpy"></i> {{payInfo.totalPrice}} </span>
        <el-image :src="seconds > 0 ? payInfo.img : ''" style="width: 200px; height: 200px"
          fit="fill"></el-image>
        <span>付款后自动到账 未到账可联系我们</span>
        <span>{{`${seconds} 秒`}}</span>
        <table class="table">
          <tr class="tr">
            <td class="td">用户名</td>
            <td> {{nickname}} </td>
          </tr>
          <tr class="tr">
            <td class="td">单号</td>
            <td>{{payInfo.uuid}}</td>
          </tr>
          <tr class="tr">
            <td class="td">创建时间</td>
            <td> {{mdayjs(payInfo.timeMillis).format('YYYY-MM-DD HH:mm:ss')}} </td>
          </tr>
          <tr class="tr">
            <td class="td">过期时间</td>
            <td>
              {{mdayjs(payInfo.timeMillis).add(payInfo.expireMillis, 'millisecond').format('YYYY-MM-DD HH:mm:ss')}}
            </td>
          </tr>
        </table>
      </div>

      <span slot="footer">
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import dayjs from 'dayjs'
import { useMainStore } from '@/js/store.js'
import conn_webSocket from '@/js/webSocket.js'

export default {
  name: 'charge_on',
  data () {
    //这里存放数据
    return {
      store: useMainStore(),
      mdayjs: dayjs,
      tableData: [],
      orderId: '',
      dialogVisible: false,
      payInfo: {},
      interval: null,
      seconds: 0,
      nickname: JSON.parse(localStorage.getItem('userInfo')).nickname,
    }
  },
  beforeRouteLeave (to, from, next) {
    if (this.interval != null) {
      clearInterval(this.interval);
      this.dialogVisible = false;
    }
    next();
  },
  //方法集合
  methods: {
    /**
     * @description: 定时器方法
     * @param {*}
     * @return {*}
     * @author: 小花
     */
    handlerSecond () {
      if (this.payInfo == null) return;
      let end = dayjs(this.payInfo.timeMillis).add(this.payInfo.expireMillis, 'millisecond');
      this.interval = setInterval(() => {
        let start = dayjs()
        let diff = end.diff(start, 'second');
        if (diff < 0) {
          clearInterval(this.interval);
          localStorage.removeItem(`payInfo-${this.orderId}`)
          return;
        }
        this.seconds = diff;
      }, 1000);
    },
    pay () {
      this.connectSocket();

      if (localStorage.getItem(`payInfo-${this.orderId}`) != null) {
        if (this.interval == null) this.handlerSecond();
        this.dialogVisible = true;
        return;
      }

      // 获取凭证码
      let code = localStorage.getItem(this.orderId);
      if (code == null) {
        this.$message.error("缴费凭证已失效，请重试。");
        this.$router.go(-1);
        return;
      }
      let socket = sessionStorage.getItem("socketID");
      this.axios.post("/userHome/pay", { code, socket }).then(res => {
        if (res.data.code == 43002) {
          localStorage.removeItem(this.orderId);
          this.$message.error("缴费凭证已失效，请重试。");
          this.$router.go(-1);
          return;
        }
        if (res.data.code != 43000) {
          this.$message.error(res.data.msg);
          return;
        }
        this.$message.success(res.data.msg);
        this.payInfo = res.data.data;
        localStorage.setItem(`payInfo-${this.orderId}`, JSON.stringify(res.data.data));
        // 开启计时
        this.handlerSecond();
        this.dialogVisible = true;
      })
    },
    connectSocket () {
      let path = 'pay'
      if (this.store.paySocket.close) this.store.paySocket.close();

      this.store.paySocket = conn_webSocket(path);

      this.store.paySocket.onopen = () => {
        console.log(`${path}连接成功`);
      };


      this.store.paySocket.onmessage = e => {
        let res = JSON.parse(e.data)
        if (res.code !== 43000) {
          this.$message.error(res.msg);
          return;
        }
        this.dialogVisible = false;
        clearInterval(this.interval);
        localStorage.removeItem(`payInfo-${this.orderId}`);
        localStorage.removeItem(this.orderId);
        this.$message.success(res.msg);
        this.store.waitPayOrders = res.data;
        this.tableData = [];
        this.getRouterQuery();
      };

      this.store.paySocket.onclose = () => {
        console.log(`${path}连接关闭`);
      };

      this.store.paySocket.onerror = () => {
        console.log(`${path}连接失败`);
      };
    },
    /**
     * @description: 页面数据初始化方法
     * @param {*}
     * @return {*}
     * @author: 小花
     */
    getRouterQuery () {
      this.orderId = this.$route.query.orderId;

      this.store.waitPayOrders.forEach(v => {
        if (v.orderId == this.orderId) this.tableData.push(v);
      });


      let payInfo = localStorage.getItem(`payInfo-${this.orderId}`);
      if (payInfo != null) this.payInfo = JSON.parse(payInfo);
    },
    checkPayStatus () {
      // 未缴费（显示缴费按钮）
      if (this.tableData.find(v => v.chargeStatus == false)) return true;
      localStorage.removeItem(`payInfo-${this.orderId}`);//清空支付信息
      localStorage.removeItem(this.orderId);//清空code
      return false;
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.getRouterQuery();
  }
}
</script>

<style lang='scss' scoped>
//@import url(); 引入公共css类
.chargeOn_container {
  .descriptionsStyle {
    margin-top: 1rem;
  }
  .dialog-header {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    .dialog-header-price {
      color: #f56c6c;
      font-weight: bold;
      font-size: 2rem;
    }
  }
  .dialog-footer {
    text-align: center;
    margin-top: 1rem;
  }
  .table {
    display: table;
    border-collapse: collapse;
    width: 400px;
    height: 100px;
    border: solid 1px gray;
    .tr {
      display: table-row;
      border: solid 1px gray;
    }
    .td {
      display: table-cell;
      width: 100px;
      text-align: center;
      vertical-align: middle;
      border: solid 1px gray;
      table-layout: fixed;
    }
  }
}
</style>